package edu.java.ishop.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;
import javax.sql.DataSource;

import edu.java.ishop.dao.UserRoleDao;
import edu.java.ishop.model.RoleName;
import edu.java.ishop.model.User;
import edu.java.ishop.model.UserRole;

@Named
public class UserRoleDatabaseDao implements UserRoleDao {

	@Inject
	private DataSource dataSource;
	public UserRoleDatabaseDao() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void delete(long Id) {
		// TODO Auto-generated method stub

	}

	@Override
	public UserRole getById(long Id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<UserRole> getAll() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean save(UserRole model) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void delete(UserRole model) {
		// TODO Auto-generated method stub

	}

	@Override
	public UserRole getUserIdAndRole(long userId, RoleName roleName) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public UserRole getByUserId(long userId) {
		UserRole result = null;
		try(Connection conn = dataSource.getConnection();
				PreparedStatement pstmt = conn.prepareStatement("select ur.id, ur.userid, u.username, u.password, ur.rolename "+
		" from \"user\" u, user_role ur where u.id = ur.userid and ur.userid = ?");){
				
			pstmt.setLong(1,userId);
			ResultSet rs = pstmt.executeQuery();
			
			if(rs.next()){
				result = new UserRole(rs.getLong(1));
				
				User user = new User(rs.getLong(2));
				user.setUsername(rs.getString(3));
				user.setPassword(rs.getString(4));
				result.setUser(user);
				result.setRoleName(RoleName.valueOf(rs.getString(5)));
			}
		}catch(SQLException e){
			throw new RuntimeException(e);
		}
		return result;
	}

}
